package com.macro.mall.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.macro.mall.common.annotation.AccessLimit;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dto.*;
import com.macro.mall.model.OmsOrder;
import com.macro.mall.service.OmsOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单管理Controller
 *
 * @author macro
 * @date 2018/10/11
 */
@Controller
@Api(tags = "OmsOrderController")
@Tag(name = "OmsOrderController", description = "订单管理")
@RequestMapping("/order")
@AllArgsConstructor
public class OmsOrderController {

    private final OmsOrderService orderService;

    @AccessLimit
    @ApiOperation("查询订单")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<OmsOrder>> list(OmsOrderQueryParam queryParam,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<OmsOrder> orderList = orderService.list(queryParam, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(orderList));
    }

    @AccessLimit
    @ApiOperation("批量发货")
    @RequestMapping(value = "/update/delivery", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> delivery(@RequestBody List<OmsOrderDeliveryParam> deliveryParamList) {
        int count = orderService.delivery(deliveryParamList);
        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @AccessLimit
    @ApiOperation("批量关闭订单")
    @RequestMapping(value = "/update/close", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> close(@RequestParam("ids") List<Long> ids, @RequestParam String note) {
        int count = orderService.close(ids, note);
        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @AccessLimit
    @ApiOperation("批量删除订单")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids) {
        int count = orderService.delete(ids);
        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @AccessLimit
    @ApiOperation("获取订单详情：订单信息、商品信息、操作记录")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<OmsOrderDetail> detail(@PathVariable Long id) {
        return CommonResult.success(orderService.detail(id));
    }

    @AccessLimit
    @ApiOperation("修改收货人信息")
    @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) {
        int count = orderService.updateReceiverInfo(receiverInfoParam);
        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @AccessLimit
    @ApiOperation("修改订单费用信息")
    @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
        int count = orderService.updateMoneyInfo(moneyInfoParam);
        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @AccessLimit
    @ApiOperation("备注订单")
    @RequestMapping(value = "/update/note", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> updateNote(@RequestParam("id") Long id,
                                           @RequestParam("note") String note,
                                           @RequestParam("status") Integer status) {
        int count = orderService.updateNote(id, note, status);
        return count > 0 ? CommonResult.success(count) : CommonResult.failed();
    }

    @AccessLimit
    @ApiOperation("通过快递单号查询快递轨迹")
    @RequestMapping(value = "/getDeliveryInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> getDeliveryInfo(@RequestParam("orderId") Long id) throws Exception {
        //用户ID，快递鸟提供，注意保管，不要泄漏
        String EBusinessID = "1846626";
        //API key，快递鸟提供，注意保管，不要泄漏
        String ApiKey = "80ea6113-f0de-46c1-b4ec-e3c4494b4fc4";
        //请求url, 正式环境地址
        String ReqURL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

        String RequestData = "{" +
                "'ShipperCode':'STO'," +
                "'LogisticCode':'773277169917224'" +
                "}";
        // 组装系统级参数
        Map<String, Object> params = new HashMap<>();
        params.put("RequestData", urlEncoder(RequestData, "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", "1002");//免费订阅接口指令1008/在途监控订阅接口指令8008/地图版订阅接口指令8005
        String dataSign = encrypt(RequestData, ApiKey, "UTF-8");
        params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");
        // 以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数
        String result = HttpUtil.post(ReqURL, params);
        System.out.println("result = " + result);
        //根据公司业务处理返回的信息......
        return null;
    }

    private String MD5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuffer sb = new StringBuffer(32);
        for (int i = 0; i < result.length; i++) {
            int val = result[i] & 0xff;
            if (val <= 0xf) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    /**
     * base64编码
     * str 内容
     * charset 编码方式
     *
     * @throws UnsupportedEncodingException
     */
    private String base64(String str, String charset) throws UnsupportedEncodingException {
        String encoded = Base64.encode(str.getBytes(charset));
        return encoded;
    }

    @SuppressWarnings("unused")
    private String urlEncoder(String str, String charset) throws UnsupportedEncodingException {
        String result = URLEncoder.encode(str, charset);
        return result;
    }

    /**
     * 电商Sign签名生成
     * content 内容
     * keyValue ApiKey
     * charset 编码方式
     *
     * @return DataSign签名
     * @throws UnsupportedEncodingException ,Exception
     */
    @SuppressWarnings("unused")
    private String encrypt(String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception {
        if (keyValue != null) {
            return base64(MD5(content + keyValue, charset), charset);
        }
        return base64(MD5(content, charset), charset);
    }
}
